package com.xh.baselibrary.tts

import java.util.*

class TTSDispatcher(val ttsEngine: TTSEngine) {
    //优先级队列
    private val priorityQueue = mutableMapOf<Int, MutableList<TTSRequest>>()

    //缓存队列
    private val cacheQueue = mutableMapOf<Int, LinkedList<TTSRequest>>()

    fun addTTSQueue(ttsRequest: TTSRequest) {
        synchronized(priorityQueue) {
            val list = if (priorityQueue.containsKey(ttsRequest.priority)) {
                priorityQueue[ttsRequest.priority]!!
            } else {
                LinkedList<TTSRequest>().apply {
                    priorityQueue[ttsRequest.priority] = this
                }
            }
            if(ttsRequest.isBreaking){
                //带isBreaking 在队列前面
                for (i in list.indices) {
                    if (!list[i].isBreaking) {
                        list.add(i, ttsRequest)
                        break
                    }
                }
            }else{
                list.add(ttsRequest)
            }
        }
        promoteAndExecute()
    }


    fun promoteAndExecute() {
        if(ttsEngine.ttsPlayer.isPlaying){
            return
        }
        //每次取一个
        synchronized(priorityQueue) {
            val priorityKeyList = priorityQueue.keys.sortedByDescending { it }
            if (priorityKeyList.isNotEmpty()) {
                val linkedList = priorityQueue[priorityKeyList[0]]!!
                if (linkedList.isNotEmpty()) {
                    ttsEngine.ttsPlayer.playTTS(linkedList.removeFirst())
                }
                if (linkedList.isEmpty()) {
                    priorityQueue.remove(priorityKeyList[0])
                }
            }
        }
    }

    fun removeFromQueue(ttsRequest: TTSRequest) {
        synchronized(priorityQueue) {
            priorityQueue[ttsRequest.priority]?.remove(ttsRequest)
        }
    }

    fun removeFromQueueByID(ttsID: String) {

    }

}